from flask import Blueprint, jsonify, request
from flask_jwt_extended import create_access_token
from app.models import User
from app import db

bp = Blueprint('auth', __name__)

@bp.route('/auth/register', methods=['POST'])
def register():
    try:
        data = request.get_json()
        if not all(k in data for k in ('username', 'email', 'password')):
            return jsonify({
                'status': 'error',
                'message': 'Missing required fields'
            }), 400

        if User.query.filter_by(username=data['username']).first():
            return jsonify({
                'status': 'error',
                'message': 'Username already exists'
            }), 400

        user = User(
            username=data['username'],
            email=data['email']
        )
        user.set_password(data['password'])
        
        db.session.add(user)
        db.session.commit()

        access_token = create_access_token(identity=user.id)
        return jsonify({
            'status': 'success',
            'message': 'Registration successful',
            'data': {
                'token': access_token,
                'user': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'is_admin': user.is_admin
                }
            }
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/auth/login', methods=['POST'])
def login():
    try:
        data = request.get_json()
        if not all(k in data for k in ('username', 'password')):
            return jsonify({
                'status': 'error',
                'message': 'Missing username or password'
            }), 400

        user = User.query.filter_by(username=data['username']).first()
        if user and user.check_password(data['password']):
            access_token = create_access_token(identity=user.id)
            return jsonify({
                'status': 'success',
                'message': 'Login successful',
                'data': {
                    'token': access_token,
                    'user': {
                        'id': user.id,
                        'username': user.username,
                        'email': user.email,
                        'is_admin': user.is_admin
                    }
                }
            })
        return jsonify({
            'status': 'error',
            'message': 'Invalid username or password'
        }), 401
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 